package railRoad.web.slaves;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import railRoad.User;
import railRoad.web.slaves.interfaces.ISlaveServlet;
import railRoad.worker.FactoryRW;

public class LoginServlet implements ISlaveServlet {

	public void work(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, ServletException {

		Map<?, ?> parameterMap = req.getParameterMap();

		String uri = "/index.jsp";
		
		req.getSession(true).removeAttribute("admin");
		
		if (parameterMap.containsKey("login")
				&& parameterMap.containsKey("password")) {
			String login = (String)req.getParameterValues("login")[0];
			String pass = (String)req.getParameterValues("password")[0];

			if (login != null && login.length() > 0) {

				User user = new User();

				user = FactoryRW.select(user, login);

				if (user != null) {
					if (user.getPassword().equals(pass)) {
						req.getSession(true).setAttribute("auth", Boolean.TRUE);
						req.getSession().removeAttribute("notAdmin");
						req.getSession().removeAttribute("cantLogin");
						req.getSession().setAttribute("user_id",
								user.getUser_id());
						req.getSession().setAttribute("passanger_id",
								user.getHuman_id());

						if (user.isAdmin())
							req.getSession()
									.setAttribute("admin", Boolean.TRUE);
					}// if password
					else
						req.getSession()
								.setAttribute("cantLogin", Boolean.TRUE);
				}// if user

				uri = (String) req.getSession().getAttribute("page");
				req.getSession().removeAttribute("page");

				if (uri == null)
					uri = "/index.jsp";
			}//if login
		}//if parameterMap
		resp.sendRedirect(uri);
	}//work
}//LoginServlet
